//
//  GameViewController.m
//  NBAPro
//
//  Created by 李广松 on 16/6/26.
//  Copyright © 2016年 WYH. All rights reserved.
//

#import "GameViewController.h"

@interface GameViewController () {
    UITableView *gameInfoTableView;
    NSArray *gameArr;
    
    UIView *dateView;
    UIDatePicker *datePicker;
    
    NSString *gameDateFormat;
    
    UILabel *dateLab;
    UILabel *gameNumLab;
}

@end

@implementation GameViewController

- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor clearColor];
    
    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)];;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    gameDateFormat = [dateFormatter stringFromDate:today];
    
    
    [self getGameInfo];
}



#pragma mark - 获取信息

- (void)getGameInfo {
    
    NSString *urlStr = [[NSString alloc] initWithFormat:@"%@scoreboard/%@/games.json",API_BASE_URL_NBA_DATA, gameDateFormat];
    NSURL *url = [[NSURL alloc] initWithString: urlStr];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error) {
            NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSDictionary *sports_contentDic = dataDic[@"sports_content"];
            NSDictionary *gamesDic = sports_contentDic[@"games"];
            [self performSelectorOnMainThread:@selector(showGameInfo:) withObject:gamesDic waitUntilDone:YES];
        }
    }];
    
    [dataTask resume];
}


- (void)showGameInfo:(NSDictionary *)gamesDic {
    if ([gamesDic isKindOfClass:[NSDictionary class]]) {
        gameArr = gamesDic[@"game"];
    }
    else {
        gameArr = @[@""];
    }
    
    
    
    if (dateView == NULL) {
        [self createTitleAndCalendarAndTalbeView];
    }
    else {
        
        [gameInfoTableView reloadData];
        
        gameNumLab.text = [[NSString alloc] initWithFormat:@"%lu Games", (unsigned long)gameArr.count];

    }
    
    
}

#pragma mark - 点击事件
- (void)touchCalender {
    if (dateView.frame.origin.y == self.view.frame.size.height) {
        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        CGPoint point = dateView.center;
        point.y -= 270;
        [dateView setCenter:point];
        [UIView commitAnimations];

    }
    
}

- (void)touchCalenderCancel {
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    CGPoint point = dateView.center;
    point.y += 270;
    [dateView setCenter:point];
    [UIView commitAnimations];

}

- (void)touchCalenderConfirm {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    CGPoint point = dateView.center;
    point.y += 270;
    [dateView setCenter:point];
    [UIView commitAnimations];
    
    NSDate *date = datePicker.date;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateLab.text = [dateFormatter stringFromDate:date];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    gameDateFormat = [dateFormatter stringFromDate:date];
    
    
    [self getGameInfo];
}



#pragma mark - UITableViewDelegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return gameArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    GameTalbeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell) {
        cell = [[GameTalbeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    
    if ([gameArr[indexPath.row] isKindOfClass:[NSDictionary class]]) {
        
        cell.groundView.backgroundColor = [GetInfo getTeamColorWithTeamName:gameArr[indexPath.row][@"home"][@"nickname"]];
        
        cell.leftTeamIconImgView.image = [UIImage imageNamed: [gameArr[indexPath.row][@"visitor"][@"team_key"] lowercaseString]];
        
        

        cell.rightTeamIconImgView.image = [UIImage imageNamed:[gameArr[indexPath.row][@"home"][@"team_key"] lowercaseString]];
        
        cell.leftCityLab.text = gameArr[indexPath.row][@"visitor"][@"city"];
        cell.leftNameLab.text = gameArr[indexPath.row][@"visitor"][@"nickname"];
        

        cell.rightCityLab.text = gameArr[indexPath.row][@"home"][@"city"];
        cell.rightNameLab.text = gameArr[indexPath.row][@"home"][@"nickname"];
        
        
        cell.leftScoreLab.text = gameArr[indexPath.row][@"visitor"][@"score"];
        cell.rightScoreLab.text = gameArr[indexPath.row][@"home"][@"score"];
                
    }
    
    
    
    cell.userInteractionEnabled = YES;
    
    return cell;
}


#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    GameDetailViewController *gameDetailViewController = [[GameDetailViewController alloc] initWithGameDate:gameDateFormat AndGameId:gameArr[indexPath.row][@"id"]];
    [self.navigationController pushViewController:gameDetailViewController animated:YES];
    
}



#pragma mark - 界面


- (void)createTitleAndCalendarAndTalbeView {
    gameInfoTableView = [self createTableViewWithFrame:CGRectMake(0, 150 + 8, self.view.frame.size.width, self.view.frame.size.height - 150 - 16)];
    
    UIView *titleView = [self createTitleViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 150) AndBackgroundColor:[UIColor colorWithRed:65/255.0 green:148/255.0 blue:231/255.0 alpha:1]];
    [self.view addSubview:titleView];
    
    
    [self createCalendarIconWithFrame:CGRectMake(self.view.frame.size.width - 40, 8, 20, 20)];
    
    
    [self createCalendarView];
    
}



- (void)createCalendarView {

    [self createCalendarModeView];
    
    //日历设置为中文
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    datePicker.locale = locale;
    
    UIButton *cancelBtn = [self createCalendarButtonWithFrame:CGRectMake(80, datePicker.frame.origin.y + datePicker.frame.size.height, 100, 30) AndTitle:@"取 消" AndTarget:@selector(touchCalenderCancel)];
    [dateView addSubview:cancelBtn];
    
    UIButton *confirmBtn = [self createCalendarButtonWithFrame:CGRectMake(self.view.frame.size.width - 80 - 100, cancelBtn.frame.origin.y, 100, 30) AndTitle:@"确认" AndTarget:@selector(touchCalenderConfirm)];
    [dateView addSubview:confirmBtn];
    
}

- (UIButton *)createCalendarButtonWithFrame:(CGRect)frame AndTitle:(NSString *)title AndTarget:(SEL)selector{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.layer.borderWidth = 1;
    button.layer.cornerRadius = 5;
    [button addTarget:self action:selector forControlEvents:UIControlEventTouchUpInside];
    
    return button;
    
}

-(void)createCalendarModeView {
    dateView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 230 + 40)];
    dateView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:dateView];
    
    datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, dateView.frame.size.width, 230)];
    datePicker.datePickerMode = UIDatePickerModeDate;
    [dateView addSubview:datePicker];
}

- (void)createCalendarIconWithFrame:(CGRect)frame {
    UIImageView *calendarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40, 8, 20, 20)];
    calendarImgView.image = [UIImage imageNamed:@"calendar"];
    [self.view addSubview:calendarImgView];
    
    UIButton *button = [CreateControl createButtonWithFrame:calendarImgView.frame AndText:@"" AndTextColor:[UIColor clearColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:20];
    [button addTarget:self action:@selector(touchCalender) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}


- (UITableView *)createTableViewWithFrame:(CGRect)frame {
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:tableView];
    
    
    return tableView;

}

- (UIView *)createTitleViewWithFrame:(CGRect)frame AndBackgroundColor: (UIColor *)backgroundColor {
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    view.backgroundColor = backgroundColor;
    
    dateLab = [self createTitleDateLabWithFrame:CGRectMake(20, 35, 200, 35)];
    
    gameNumLab = [self createTitleGameNumberLabelWithFrame:CGRectMake(dateLab.frame.origin.x, dateLab.frame.origin.y + dateLab.frame.size.height, 100, 15)];
    
    [view addSubview:dateLab];
    [view addSubview:gameNumLab];
    
    return view;
}

- (UILabel *)createTitleDateLabWithFrame:(CGRect)frame {
    NSDate *today = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)];;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *gameDate = [dateFormatter stringFromDate:today];
    NSString *timeStr = gameDate;
    
    UILabel *label = [CreateControl createLabelWithFrame:frame AndText:timeStr AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:35];
    label.textAlignment = NSTextAlignmentLeft;
    
    return label;
    
}

- (UILabel *)createTitleGameNumberLabelWithFrame:(CGRect)frame {
    NSString *numStr =[[NSString alloc] initWithFormat:@"%lu Games", (unsigned long)gameArr.count];
    UILabel *label = [CreateControl createLabelWithFrame:frame AndText:numStr AndTextColor:[UIColor whiteColor] AndBackgroundColor:[UIColor clearColor] AndTextFont:15];
    label.textAlignment = NSTextAlignmentLeft;
    
    return label;
}



#pragma mark - other
- (CGSize)getSizeWithString:(NSString *)string AndFont:(float)font{
    CGSize size = [string sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]}];
    return size;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
